import { Injectable, Logger } from "@nestjs/common";
import { Cron, CronExpression } from "@nestjs/schedule";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource } from "typeorm";
import { CharacterTrainingEntity } from "../entities/character-training.entity";
import { CharacterEntity } from "../entities/character.entity";
import { PrivateMessageEntity } from "../entities/private-message.entity";
import { CharacterAttributeService } from "./character-attribute.service";
import { CharacterService } from "./character.service";

@Injectable()
export class CharacterTrainingSchedulerService {
  private readonly logger = new Logger(CharacterTrainingSchedulerService.name);

  constructor(
    @InjectRepository(CharacterTrainingEntity)
    private readonly characterTrainingRepository: Repository<CharacterTrainingEntity>,
    @InjectRepository(CharacterEntity)
    private readonly characterRepository: Repository<CharacterEntity>,
    @InjectRepository(PrivateMessageEntity)
    private readonly privateMessageRepository: Repository<PrivateMessageEntity>,
    private readonly dataSource: DataSource,
    private readonly characterAttributeService: CharacterAttributeService,
    private readonly characterService: CharacterService
  ) {}

  /**
   * 每5分钟检测训练是否完成
   */
  @Cron("*/5 * * * *")
  async checkTrainingCompletion() {
    try {
      this.logger.log("开始检测训练完成状态...");

      // 查询所有正在训练中的记录
      const trainingRecords = await this.characterTrainingRepository.find({
        where: {
          isTraining: true,
          trainingStatus: 1, // 训练中状态
        },
      });

      if (trainingRecords.length === 0) {
        this.logger.log("没有正在进行的训练");
        return;
      }

      this.logger.log(`发现 ${trainingRecords.length} 个正在进行的训练`);

      const now = new Date();
      const completedTrainings = [];

      for (const training of trainingRecords) {
        // 检查训练是否完成
        if (training.trainingEndTime && now >= training.trainingEndTime) {
          completedTrainings.push(training);
        }
      }

      if (completedTrainings.length === 0) {
        this.logger.log("没有训练完成");
        return;
      }

      this.logger.log(
        `发现 ${completedTrainings.length} 个训练已完成，开始处理...`
      );

      // 处理每个完成的训练
      for (const training of completedTrainings) {
        await this.processCompletedTraining(training);
      }

      this.logger.log(
        `训练完成检测完成，处理了 ${completedTrainings.length} 个训练`
      );
    } catch (error) {
      this.logger.error("检测训练完成状态时发生错误:", error);
    }
  }

  /**
   * 处理完成的训练
   */
  private async processCompletedTraining(training: CharacterTrainingEntity) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      this.logger.log(`处理角色 ${training.characterId} 的训练完成`);

      // 获取角色信息（用于私信称呼）
      const character = await queryRunner.manager.findOne(CharacterEntity, {
        where: { id: training.characterId },
      });

      if (!character) {
        this.logger.warn(`角色 ${training.characterId} 不存在，跳过处理`);
        return;
      }

      // 使用1207阶段预存的待领取经验（与1208一致，不在此结算）
      const expToClaim = Number((training as any).pendingExp || 0);

      // 更新训练记录状态
      await queryRunner.manager.update(
        CharacterTrainingEntity,
        { id: training.id },
        {
          isTraining: false,
          trainingStatus: 2, // 设置为已完成
          trainingStartTime: undefined,
          trainingEndTime: undefined,
          trainingHours: 0,
        }
      );

      // 发送系统私信通知玩家训练完成（提示前往训练场领取经验）
      await this.sendTrainingCompletionMessage(
        queryRunner,
        training.characterId,
        character.name,
        expToClaim
      );

      await queryRunner.commitTransaction();
      this.logger.log(
        `角色 ${character.name} 训练已完成，待领取经验 ${expToClaim}`
      );
    } catch (error) {
      await queryRunner.rollbackTransaction();
      this.logger.error(
        `处理训练完成失败: characterId=${training.characterId}`,
        error
      );
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 发送训练完成私信
   */
  private async sendTrainingCompletionMessage(
    queryRunner: any,
    characterId: number,
    characterName: string,
    expToClaim: number
  ) {
    try {
      const message = `训练已完成，请前往训练场领取经验 ${expToClaim}`;

      const privateMessage = queryRunner.manager.create(PrivateMessageEntity, {
        senderId: 0, // 系统发送
        receiverId: characterId,
        content: message,
        messageType: "system",
        isRead: false,
        created_at: new Date(),
      });

      await queryRunner.manager.save(privateMessage);

      this.logger.log(
        `已向角色 ${characterName} 发送训练完成私信（待领 ${expToClaim}）`
      );
    } catch (error) {
      this.logger.error(
        `发送训练完成私信失败: characterId=${characterId}`,
        error
      );
    }
  }

  /**
   * 获取训练经验倍率
   * 根据等级确定训练经验倍率
   */
  private getTrainingMultiplier(level: number): number {
    if (level >= 1 && level <= 40) {
      return 150; // 1-40级：150倍
    } else if (level >= 41 && level <= 70) {
      return 200; // 41-70级：200倍
    } else if (level >= 71 && level <= 160) {
      return 300; // 71-160级：300倍
    }
    return 150; // 默认150倍
  }
}
